﻿
$.reload = function () {
    location.reload();
    return false;
}
$.loading = function (bool, text) {
    var $loadingpage = top.$("#loadingPage");
    var $loadingtext = $loadingpage.find('.loading-content');
    if (bool) {
        $loadingpage.show();
    } else {
        if ($loadingtext.attr('istableloading') == undefined) {
            $loadingpage.hide();
        }
    }
    if (!!text) {
        $loadingtext.html(text);
    } else {
        $loadingtext.html("数据加载中，请稍候…");
    }
    $loadingtext.css("left", (top.$('body').width() - $loadingtext.width()) / 2 - 50);
    $loadingtext.css("top", (top.$('body').height() - $loadingtext.height()) / 2);
}
$.request = function (name) {
    var search = location.search.slice(1);
    var arr = search.split("&");
    for (var i = 0; i < arr.length; i++) {
        var ar = arr[i].split("=");
        if (ar[0] == name) {
            if (unescape(ar[1]) == 'undefined') {
                return "";
            } else {
                return unescape(ar[1]);
            }
        }
    }
    return "";
}
$.browser = function () {
    var userAgent = navigator.userAgent;
    var isOpera = userAgent.indexOf("Opera") > -1;
    if (isOpera) {
        return "Opera"
    };
    if (userAgent.indexOf("Firefox") > -1) {
        return "FF";
    }
    if (userAgent.indexOf("Chrome") > -1) {
        if (window.navigator.webkitPersistentStorage.toString().indexOf('DeprecatedStorageQuota') > -1) {
            return "Chrome";
        } else {
            return "360";
        }
    }
    if (userAgent.indexOf("Safari") > -1) {
        return "Safari";
    }
    if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
        return "IE";
    };
}
$.download = function (url, data, method) {
    if (url && data) {
        data = typeof data == 'string' ? data : jQuery.param(data);
        var inputs = '';
        $.each(data.split('&'), function () {
            var pair = this.split('=');
            inputs += '<input type="hidden" name="' + pair[0] + '" value="' + pair[1] + '" />';
        });
        $('<form action="' + url + '" method="' + (method || 'post') + '">' + inputs + '</form>').appendTo('body').submit().remove();
    };
};
$.modalOpen = function (options) {
    var defaults = {
        id: null,
        title: '系统窗口',
        width: "200px",
        height: "200px",
        url: '',
        type: 2,
        shade: 0.3,
        maxmin: false,
        callBack: null,
        scrollbar: false,
        auto:false,
    };
    var options = $.extend(defaults, options);
    var _width = top.$(window).width() > parseInt(options.width.replace('px', '')) ? options.width : top.$(window).width() + 'px';
    var _height = top.$(window).height() > parseInt(options.height.replace('px', '')) ? options.height : top.$(window).height() + 'px';
    var index = top.layer.open({
        id: options.id,
        type: options.type,
        shade: options.shade,
        title: options.title,
        fix: true,
        maxmin: options.maxmin,
        area: [_width, _height],
        content: options.url,
        scrollbar: options.scrollbar,
        success: function (layor) {
            if (options.auto) {
                top.layer.iframeAuto(index)
            }
        }
    });
}

$.modalConfirm = function (content, callBack) {
    top.layer.confirm(content, {
        icon: "fa-exclamation-circle",
        title: "系统提示",
        btn: ['确认', '取消'],
        btnclass: ['btn btn-primary', 'btn btn-danger'],
    }, function () {
        callBack(true);
    }, function () {
        callBack(false)
    });
}
$.modalAlert = function (content, type) {
    var icon = "";
    if (type == 'success') {
        icon = "fa-check-circle";
    }
    if (type == 'error') {
        icon = "fa-times-circle";
    }
    if (type == 'warning') {
        icon = "fa-exclamation-circle";
    }
    top.layer.alert(content, {
        icon: icon,
        title: "系统提示",
        btn: ['确认'],
        btnclass: ['btn btn-primary'],
    });
}
$.modalMsg = function (content, type) {
    if (type != undefined) {
        var icon = "";
        if (type == 'success') {
            icon = "fa-check-circle";
        }
        if (type == 'error') {
            icon = "fa-times-circle";
        }
        if (type == 'warning') {
            icon = "fa-exclamation-circle";
        }
        top.layer.msg(content, { icon: icon, time: 3000, shift: 5 });
        top.$(".layui-layer-msg").find('i.' + icon).parents('.layui-layer-msg').addClass('layui-layer-msg-' + type);
    } else {
        top.layer.msg(content);
    }
}
$.modalClose = function () {
    var index = top.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    var $IsdialogClose = top.$("#layui-layer" + index).find('.layui-layer-btn').find("#IsdialogClose");
    var IsClose = $IsdialogClose.is(":checked");
    if ($IsdialogClose.length == 0) {
        IsClose = true;
    }
    if (IsClose) {
        top.layer.close(index);
    } else {
        location.reload();
    }
}
$.modaliframeAuto = function () {
    var index = top.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    top.layer.iframeAuto(index);
}
$.submitForm = function (options) {
    var defaults = {
        url: "",
        param: [],
        loading: "正在提交数据...",
        success: null,
        error:null,
        close: true
    };
    var options = $.extend(defaults, options);
    //数据未修改
    if (!options.param["isModify"]) {
        $.modalMsg("数据未修改，请修改数据提交", "warning");
        return false;
    }
    $.loading(true, options.loading);
    window.setTimeout(function () {
        //if ($('[name=__RequestVerificationToken]').length > 0) {
        //    options.param["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
        //}
        $.ajax({
            url: options.url,
            data: options.param,
            type: "post",
            dataType: "json",
            success: function (data) {
                if (data.Status == "success") {
                    options.success(data);
                    $.modalMsg(data.Message, data.Status);
                    if (options.close == true) {
                        $.modalClose();
                    }                    
                }
                else if(data.Status == "error")
                {
                    options.error(data);
                    $.loading(false);
                }
                else {                    
                    $.modalAlert(data.Message, data.Status);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.loading(false);
                $.modalMsg(errorThrown, "error");
            },
            beforeSend: function () {
                $.loading(true, options.loading);
            },
            complete: function () {
                $.loading(false);
            }
        });
    }, 500);
}
/***tyj 2017年1月10日10:29:44 ajax提交数据**/
$.submitAjax = function (options) {
    var defaults = {
        url: "",
        param: [],
        loading: "正在提交数据...",
        success: null,
        close: true
    };
    var options = $.extend(defaults, options);
    $.loading(true, options.loading);
    window.setTimeout(function () {
        $.ajax({
            url: options.url,
            data: options.param,
            type: "post",
            dataType: "json",
            success: function (data) {
                if (data.Status == "success") {
                    options.success(data);
                    $.modalMsg(data.Message, data.Status);
                } else {
                    $.modalAlert(data.Message, data.Status);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.loading(false);
                $.modalMsg(errorThrown, "error");
            },
            beforeSend: function () {
                $.loading(true, options.loading);
            },
            complete: function () {
                $.loading(false);
            }
        });
    }, 500);
}


$.deleteForm = function (options) {
    var defaults = {
        prompt: "注：您确定要删除该项数据吗？",
        url: "",
        param: [],
        loading: "正在删除数据...",
        success: null,
        close: true
    };
    var options = $.extend(defaults, options);
    //if ($('[name=__RequestVerificationToken]').length > 0) {
    //    options.param["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
    //}
    $.modalConfirm(options.prompt, function (r) {
        if (r) {
            $.loading(true, options.loading);
            window.setTimeout(function () {
                $.ajax({
                    url: options.url,
                    data: options.param,
                    type: "post",
                    dataType: "json",
                    success: function (data) {
                        if (data.Status == "success") {
                            options.success(data);
                            $.modalMsg(data.Message, data.Status);
                        } else {
                            $.modalAlert(data.Message, data.Status);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.loading(false);
                        $.modalMsg(errorThrown, "error");
                    },
                    beforeSend: function () {
                        $.loading(true, options.loading);
                    },
                    complete: function () {
                        $.loading(false);
                    }
                });
            }, 500);
        }
    });
}
$.fn.formSerialize = function (formdate) {
    var element = $(this);
    if (!!formdate) {
        for (var key in formdate) {
            var $id = element.find('#' + key);
            var value = $.trim(formdate[key]).replace(/&nbsp;/g, '');
            var type = $id.attr('type');
            switch (type) {
                case "radio":
                    var $radio = element.find("input[name='" + key + "'][value = '" + value + "']");
                    $radio.prop("checked", 'checked');
                    $id.data("value", value);
                    break;
                case "checkbox":
                    if (value == "true") {
                        $id.attr("checked", 'checked');
                        $id.data("value", true);
                    } else {
                        $id.removeAttr("checked");
                        $id.data("value", false);
                    }
                    break;
                case "select":
                    $id.val(value).trigger("change");
                    $id.data("value", value);
                    break;
                case "password":
                    $id.data("value", value);
                    break;
                default:
                    $id.val(value);
                    $id.data("value", value);
                    break;
            }
        };
        return false;
    }
    var postdata = {};
    postdata["isModify"] = false;
    //主键
    var formId = element.find('input.formId').val();
    element.find('input,select,textarea').each(function (r) {
        var $this = $(this);
        var id = $this.attr('id');
        var type = $this.attr('type');
        if (id) {
            switch (type) {
                case "radio":
                    var $radio = element.find("input[name='" + $this.attr("name") + "']:checked");
                    postdata[id] = $radio.val();
                    if (postdata[id] != $this.data("value")) {
                        postdata["isModify"] = true;
                    }
                    break;
                case "checkbox":
                    postdata[id] = $this.is(":checked");
                    if (postdata[id] != $this.data("value")) {
                        postdata["isModify"] = true;
                    }
                    break;
                case "select":
                    var value = $this.find("option:selected").val() == "" ? null : $this.find("option:selected").val();
                    postdata[id] = $this.find("option:selected").val();
                    if (postdata[id] != $this.data("value")) {
                        postdata["isModify"] = true;
                    }
                    break;
                    //密码加密
                default:
                    //var value = $this.val() == "" ? "&nbsp;" : $this.val();
                    //if (!formId) {
                    //    //新建
                    //    value = value.replace(/&nbsp;/g, '');
                    //}
                    //var value = $this.val();
                    postdata[id] = $this.val();
                    if (postdata[id] != $this.data("value")) {
                        postdata["isModify"] = true;
                    }
                    break;
            }
            //判断是否有修改数据
            //if (postdata[id] != $this.data("value")) {
            //    postdata["isModify"] = true;
            //}
        }
    });
    //if ($('[name=__RequestVerificationToken]').length > 0) {
    //    postdata["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
    //}
    return postdata;
};
$.jsonWhere = function (data, action) {
    if (action == null) return;
    var reval = new Array();
    $(data).each(function (i, v) {
        if (action(v)) {
            reval.push(v);
        }
    });
    return reval;
}

//关于Guid的处理 刘立军 2017-1-24
$.IsGuid=function(data)
{
    var reg = /^^\w{8}-(\w{4}-){3}\w{12}$$/;
    return reg.test(data);
}
$.NewGuid=function()
{
    return "00000000-0000-0000-0000-000000000000";
}
$.fn.formInit = function (guidFieldName) {
    var element = $(this);
    element.find('input,select,textarea').each(function (r) {
        var $this = $(this);
        var id = $this.attr('id');
        var type = $this.attr('type');
        if (id) {
            if (guidFieldName && id == guidFieldName)
            {                
                $this.val($.NewGuid);                
            }
            else {
                switch (type) {
                    case "radio":
                        //element.find("input[name='" + $this.attr("name") + "']").removeAttr("checked");;
                        //$this.prop("checked", 'true');
                        $this.prop("checked", 'checked');
                        break;
                    case "checkbox":
                        $this.attr("checked", 'checked');
                        break;
                    case "select":
                        $this.find("option:first").attr("selected", true);
                        $this.val($this.find("option:first").val());
                        break;
                    case "number":
                        $this.val("0");
                        break;
                    default:
                        //对Guid做特殊处理 2017-1-23 刘立军                   
                        if ($.IsGuid($this.val())) {
                            $this.val($.NewGuid);
                        }
                        else {
                            $this.val("");
                        }
                        break;
                }
            }            
        }
    });
};

$.fn.bindSelect = function (options) {
    var defaults = {
        id: "id",
        text: "text",
        search: false,
        url: "",
        param: [],
        change: null
    };
    var options = $.extend(defaults, options);
    var $element = $(this);
    if (options.url != "") {
        $.ajax({
            url: options.url,
            data: options.param,
            dataType: "json",
            async: false,
            success: function (data) {
                $.each(data, function (i) {
                    $element.append($("<option></option>").val(data[i][options.id]).html(data[i][options.text]));
                });
                $element.select2({
                    minimumResultsForSearch: options.search == true ? 0 : -1
                });
                $element.on("change", function (e) {
                    if (options.change != null) {
                        options.change(data[$(this).find("option:selected").index()]);
                    }
                    $("#select2-" + $element.attr('id') + "-container").html($(this).find("option:selected").text().replace(/　　/g, ''));
                });
            }
        });
    } else {
        $element.select2({
            minimumResultsForSearch: -1
        });
    }
}
Array.prototype.contains = function (needle) {
    for (i in this) {
        if (this[i] == needle) return true;
    }
    return false;
}
Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};
//cookie
